package org.example.listener;

import org.example.component.LoginInfo;
import org.example.component.UserInfo;
import org.example.config.ImConfig;
import org.example.packets.Status;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.handler.user.GroupUser;
import org.example.util.ChannelContextUtil;
import org.tio.core.ChannelContext;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ImServerUserPropListener implements ImUserPropListener {

    @Override
    public void onStatusChange(Status status) {
        // 更新所有缓存的用户状态
        User user = UserInfo.user();
        user.setStatus(status);
        ImConfig.userListener().onAfterChange(user);
//
        List<Group> groups = UserInfo.groups();
        for (Group group : groups) {
            for (GroupUser groupUser : group.getUsers()) {
                if(groupUser.getId().equals(user.getId())){
                    groupUser.setStatus(status);
                    break;
                }
            }
            UserInfo.putGroup(group);
        }
//        List<String> roomIds = groups.stream().map(Group::getRoomId).collect(Collectors.toList());

//        Set<String> userList = groups.stream()
//                .map(x -> x.getUsers().stream().map(GroupUser::getId).collect(Collectors.toList()))
//                .flatMap(Collection::stream)
//                .filter(x -> !x.equals(UserInfo.id()))
//                .collect(Collectors.toSet());
//
//        List<ChannelContext> channelContexts = ChannelContextUtil.contextList(userList);
//
//        channelContexts.forEach(x -> {
//            LoginInfo loginInfo = new LoginInfo().setChannelContext(x);
//            List<Group> groupList = loginInfo.getGroups().stream().filter(z -> roomIds.contains(z.getRoomId())).collect(Collectors.toList());
//            for (Group group : groupList) {
//                for (GroupUser groupUser : group.getUsers()) {
//                    if (groupUser.getId().equals(user.getId())) {
//                        groupUser.setStatus(status);
//                    }
//                }
//            }
//        });
//
//        ChannelContext channelContext = UserInfo.get().getChannelContext();

    }

}
